﻿// controller to manage common user functionality
angular.module('app.user').controller('UserController', [
	'$scope', 'libraryService', 'authService', '$state', '$stateParams', 'dataService',
	function ($scope, libraryService, authService, $state, $stateParams, dataService) {
		'use strict';

		var instance = this;
		// declare the model to get the authenticated user and the parameters for the state
		$scope.model =
			{
				authUser: authService.authStatus.authenticatedUser,
				params: {
					userId: $state.params.userId,
					folderId: $state.params.folderId
				},
				user: undefined
			};
		// can edit only if the model user equals the authenticated user
		$scope.canEdit = function () {
			return ($scope.model.user == null || $scope.model.user === undefined) ? false :
				$scope.model.authUser.Id === $scope.model.user.Id;
		};
		// get the user ID from the params
		var userId = $scope.model.params.userId;

		if (userId !== null && userId !== undefined) {
			// check if auth user is the user being viewed
			if ($scope.model.authUser !== null &&
				$scope.model.authUser !== undefined &&
				userId === $scope.model.authUser.Id) {
				// set model user to the auth user
				$scope.model.user = $scope.model.authUser;
			}
			else {
				// get the user info from the library service
				libraryService.getUserInfo(userId).then(function (reply) {
					// set the reply data content
					var content = reply.data.Content;

					if (content !== null && content !== undefined && content.length > 0) {
						// found the user, set the model.user value
						$scope.model.user = content[0];
					}
					else {
						// could not get the user, go to search
						$state.transitionTo('search');
					}
				});
			}
		}
		else {
			// no user id, go back to search
			$state.transitionTo('search');
		}

		// function to set the folder id to the parameter value
		$scope.setFolderId = function (value) {
			$scope.model.params.folderId = value;
		};
		// is viewing favorites when the folder ID is -1
		$scope.isViewingFavorites = function () {
			return $scope.model.params.folderId === -1;
		};
		// returns the folder Id as the parameter folder ID or the library's folder id
		$scope.getFolderId = function () {
			return $scope.model.params.folderId ||
				$scope.model.user.Library.FolderId;
		};
		
		// handle the log in reply
		this.handleLogInReply = function (reply) {
			// if authenticated set the auth user
			if (authService.authStatus.isAuthenticated) {
				$scope.model.authUser = authService.authStatus.authenticatedUser
			}
			else {
				// authentication failed, go to search
				$state.transitionTo('search');
			}
		};
		// if the authenticated user is known on initialization, try to authenticate by session
		if ($scope.model.authUser === null || $scope.model.authUser === undefined) {
			authService.sendAuthRequest(null).then(instance.handleLogInReply);
		}
	}]);